package com.ruoyi.common.utils.poi;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class ImageConcatenation {
    public static BufferedImage concatenateImages(String[] urlArray) {
        ArrayList<BufferedImage> images = new ArrayList<>();
        int totalWidth = 0;
        int maxHeight = 0;

        // 第一步：从网络URL读取所有图片，计算总宽度和最大高度
        for (String imageUrl : urlArray) {
            try {
                BufferedImage img = downloadImage(imageUrl);
                if (img != null) {
                    images.add(img);
                    totalWidth += img.getWidth();
                    maxHeight = Math.max(maxHeight, img.getHeight());
                } else {
                    System.err.println("无法读取图片: " + imageUrl);
                }
            } catch (Exception e) {
                System.err.println("下载图片时出错: " + imageUrl);
            }
        }

        // 第二步：创建结果图像，宽度为总宽度，高度为最大高度
        BufferedImage resultImage = new BufferedImage(totalWidth, maxHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resultImage.createGraphics();

        // 第三步：逐个绘制图片
        int x = 0;
        for (BufferedImage img : images) {
            if (img != null) {
                g2d.drawImage(img, x, 0, null);
                x += img.getWidth();
            }
        }

        g2d.dispose();

        // 第四步：保存结果图像
        try {
            ImageIO.write(resultImage, "PNG", new File("result1.png"));
            System.out.println("图片拼接完成，已保存为 result1.png");
        } catch (IOException e) {
            System.err.println("保存结果图片时出错");
            e.printStackTrace();
        }
        return resultImage;
    }

//    private static BufferedImage downloadImage(String imageUrl) throws IOException {
//        URL url = new URL(imageUrl);
//        BufferedImage image = ImageIO.read(url);
//        return image;
//    }
    // https://cloud-test.yunxiangfarm.cn/upload/2025/10/31/e6990d02718944d3a9c727876917b0bc.png

    public static void main(String[] args) {

        String urlList = "https://cloud-test.yunxiangfarm.cn/upload/2025/10/17/45be8d1b518b4fe68319e85a0afe33d4.jpg,https://cloud-test.yunxiangfarm.cn/upload/2025/10/17/8095451b135247f3ba1025a13383c05b.jpg,https://cloud-test.yunxiangfarm.cn/upload/2025/10/18/c3bc5c4b0e974bab864db7fbac621240.png,https://cloud-test.yunxiangfarm.cn/upload/2025/10/18/f6d9f8536fb3405faf090591d43b8b2b.jpg";

        String[] urls = urlList.split(",");

//        String[] urls = {"https://cloud-test.yunxiangfarm.cn/upload/2025/10/31/e6990d02718944d3a9c727876917b0bc.png", "https://cloud-test.yunxiangfarm.cn/upload/2025/10/31/e6990d02718944d3a9c727876917b0bc.png"};
        concatenateImages(urls);
    }

    private static BufferedImage downloadImage(String imageUrl) {
        trustAllHosts();
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setDoInput(true);

            // 设置 User-Agent 防止被拒绝
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");

            if (connection.getResponseCode() != 200) {
                System.err.println("Image download failed: " + imageUrl + " | Code: " + connection.getResponseCode());
                return null;
            }

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try (InputStream input = connection.getInputStream()) {
                byte[] buffer = new byte[4096];
                int n;
                while ((n = input.read(buffer)) != -1) {
                    output.write(buffer, 0, n);
                }
            }
            byte[] imageBytes = output.toByteArray();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
            return ImageIO.read(inputStream);
//            return output.toByteArray();
        } catch (Exception e) {
            System.err.println("Error downloading image: " + imageUrl);
            e.printStackTrace();
            return null;
        }
    }

    public static void trustAllHosts() {
        try {
            javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[]{
                    new javax.net.ssl.X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
                        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                    }
            };

            javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
